layui.use(['element','table','form','layer','util','laydate'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer;

    function loadOptions(url, projectId,eleId) {
        $.get(url, {projectId:projectId}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>全部</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item + "'>" + item + "</option>";
                    });
                    $("#"+eleId).empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    function loadCategoryList(projectId) {
        $.get('/cdsideparkmgr/cdsideparkmgrParkRecord/listCategory', {projectId:projectId}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>全部</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item + "'>" + item + "</option>";
                    });
                    $("#categoryId").empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    //执行一个laydate实例
    var beginDateInit = function(startId,endId ){
        laydate.render({
            elem: startId,
            type: 'datetime',
            done: function (value ) {
                var startDate = new Date(value).getTime();
                var endTime = new Date($(endId).val()).getTime();
                if (endTime < startDate) {
                    layer.msg('结束时间不能小于开始时间');
                    $(startId).val('');
                }
            }
        })
    }
    var endDateInit = function(startId,endId ){
        laydate.render({
            elem: endId,
            type: 'datetime',
            done: function (value ) {
                var startDate = new Date($(startId).val()).getTime();
                var endTime = new Date(value).getTime();
                if (endTime < startDate) {
                    layer.msg('结束时间不能小于开始时间');
                    $(endId).val('');
                }
            }
        })
    }

    // 停靠时间
    beginDateInit('#openBeginDate','#openEndDate');
    endDateInit('#openBeginDate','#openEndDate');

    // 停靠时间
    beginDateInit('#openBeginDate2','#openEndDate2');
    endDateInit('#openBeginDate2','#openEndDate2');

    table.render({
        elem: '#myYardTable'
        ,url:'/cdsideparkmgr/cdsideparkmgrMyProject/list'
        ,title: '项目管理'
        ,where: {"projectType":projectType}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{field:'projectNo', title:'项目编号',align:'center'}
            ,{field:'projectName', title:'项目名称',align:'center'}
            ,{field:'carNum', title:'车位总数',align:'center'}
            ,{field:'managerName', title:'车场负责人',align:'center'}
            ,{field:'managerPhone', title:'联系电话',align:'center'}
            ,{field:'addressDetail', title:'项目位置',align:'center'}
            ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',fixed: 'right',width:260}
        ]]
        ,page: true
        ,toolbar: '#toolbarDemo'
    });

    table.on('tool(myYardTable)',function (obj) {
        var data = obj.data;
        let projectId = data.id;
        switch (obj.event) {
            case 'record':
                $("#projectId").val(projectId);
                loadOptions('/cdsideparkmgr/cdsideparkmgrParkRecord/loadAreaList',projectId,'area');
                loadOptions('/cdsideparkmgr/cdsideparkmgrParkRecord/loadStallList',projectId,'stall');
                loadCategoryList(projectId);
                table.render({
                    elem: '#passRecordTable'
                    ,url:'/cdsideparkmgr/cdsideparkmgrParkRecord/list'
                    ,title: '车辆停靠记录'
                    ,where: {"projectId":projectId}
                    ,cols: [[
                        {field: 'xh',type:'numbers', title: '序号',}
                        ,{field:'carNo', title:'车牌号',align:'center'}
                        ,{field:'category', title:'车辆类别',align:'center'}
                        ,{field:'area', title:'停靠区域',align:'center'}
                        ,{field:'stall', title:'停靠车位',align:'center'}
                        ,{field:'parkTime', title:'停靠时间', sort: true,templet:
                                function(data){
                                    return formatTime(data.parkTime);
                                }}
                        ,{field:'leaveTime', title:'驶离时间', sort: true,templet:
                                function(data){
                                    return formatTime(data.leaveTime);
                                }}
                        ,{field:'stayTimeStr', title:'停车时长',align:'center'}
                        ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
                    ]]
                    ,page:true
                    ,toolbar: '#toolbarDemo'
                });
                layer.open({
                    type: 1
                    , title: '停靠记录'
                    , shadeClose: true
                    , area: ['99%', '99%']
                    , content: $('#passRecordDiv')
                    ,btn: ['确定', '取消']
                });
                break;
            case 'snapRecord':
                renderSnapRecord(projectId);
                break
            case 'carInside':
                renderCarInsideRecord(projectId);
                break

        }
    });

    function renderCarInsideRecord(projectId) {
        $("#projectId2").val(projectId);
        table.render({
            elem: '#carInsideTable'
            ,url:'/cdyardmgr/cdyardmgrPassRecord/pageCarInside'
            ,title: '场内车辆记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {type:'checkbox'},
                {type:'numbers',title:'序号'}
                ,{field:'carNo', title:'车牌号',align:'center'}
                ,{field:'category', title:'车辆类别',align:'center'}
                ,{field:'enterTime', title:'入场时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.enterTime);
                        }}
                ,{field:'stayTimeStr', title:'已停留时间',align:'center'}
                ,{field:'phone', title:'车主手机号码',align:'center'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
            ,parseData: function(res){ //res 即为原始返回的数据
                $("#carInsideTotal").html(res.carNum);
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
        });
        layer.open({
            type: 1
            , title: '场内车辆'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#carInsideDiv')
            ,btn: ['确定', '取消']
        });
    }

    $("#artificialCorrect").on('click',function () {
        let checkStatus = table.checkStatus('carInsideTable');
        let data= checkStatus.data
        if(data.length == 0){
            layer.msg("请选择需要纠正的车辆");
            return false;
        }
        $("#remark").val("");
        layer.open({
            type: 1
            , title: '人工纠正'
            , shadeClose: true
            , area: ['60%', '80%']
            , content: $('#artificialCorrectDiv')
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
                let load = layer.load();
                let arr = [];
                for (let i = 0; i < data.length; i++) {
                    arr.push({"id":data[i].id,"remark":$("#remark").val(),"carNo":data[i].carNo,"projectId":data[i].projectId});
                }
                //let param = {"id":$("#carInsideId").val(),"remark":$("#remark").val(),"isDel":1};
                $.ajax({
                    type: 'post',
                    url: '/cdyardmgr/cdyardmgrPassRecord/correctCar',
                    contentType: "application/json;charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(arr),
                    success: function (res) {
                        layer.close(load);
                        layer.msg(res.msg);
                        if(res.status == 200){
                            layer.close(index);
                            table.reload('carInsideTable');
                        }
                    },
                });
            }
        });
    });

    form.on('submit(queryCarInside)',function () {
        queryCarInside();
        return false;
    });

    function queryCarInside(){
        var projectId = $("#projectId2").val();
        var carNo = $("#searchCarNo3").val();
        var sjfw = $("#stayTime").val();
        table.reload('carInsideTable',{
            where: {projectId:projectId,carNo:carNo,sjfw:sjfw}
            ,page:  {
                curr:1
            }
        });
    }

    function renderSnapRecord(yardId) {
        $("#yardId2").val(yardId);
        table.render({
            elem: '#snapRecordTable'
            ,url:'/cdyardmgr/cdyardmgrPassRecord/listSnapRecord'
            ,title: '抓拍记录'
            ,where: {"yardId":yardId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'createTime', title:'时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.createTime);
                        }}
                ,{field:'signoName', title:'抓拍相机',align:'center'}
                ,{field: 'capPic', title: '抓拍图片', align:'center',templet:function (d) {
                        if(d.capPic){
                            return '<img onclick="previewImg(this)" style="cursor: pointer" width="30" height="25" src="'+d.capPic+'"/>';
                        }
                        return "";
                    }}
            ]]
            ,page:true
        });
        layer.open({
            type: 1
            , title: '抓拍记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#snapRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    table.on('tool(passRecordTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'image':
                $("#picture").attr("src",data.picture);
                layer.open({
                    type: 1
                    , title: '图像记录'
                    , shadeClose: true
                    , area: ['99%', '99%']
                    , content: $('#imageDiv')
                    ,btn: ['确定', '取消']
                });
                break;

        }
    });

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    form.on('submit(queryYard)',function () {
        queryYard();
        return false;
    });

    form.on('submit(queryPassRecord)',function () {
        queryPassRecord();
        return false;
    });

    function queryYard(){
        var projectName = $("#searchName").val();
        var projectNo = $("#searchCode").val();
        table.reload('myYardTable',{
            where: {projectType:projectType,projectName:projectName,projectNo:projectNo}
            ,page:  {
                curr:1
            }
        });
    }

    function queryPassRecord(){
        var projectId = $("#projectId").val();
        var carNo = $("#searchCarNo").val();
        var area = $("#area").val();
        var stall = $("#stall").val();
        var direction = $("#direction").val();
        var category = $("#categoryId").val();
        var startDate= $("#openBeginDate").val();
        var endDate= $("#openEndDate").val();
        var startDate2= $("#openBeginDate2").val();
        var endDate2= $("#openEndDate2").val();
        table.reload('passRecordTable',{
            where: {projectId:projectId,carNo:carNo,stall:stall,area:area,direction:direction,
                category:category,startDate:startDate,endDate:endDate,startDate2:startDate2,endDate2:endDate2}
            ,page:  {
                curr:1
            }
        });
    }

});
